package com.cutefool.zero.code.admin.meta.model.support;

import com.cutefool.core.kits.consts.Status;
import com.cutefool.dsl.mybatis.core.dsl.builder.QueryDsl;
import com.cutefool.dsl.mybatis.core.dsl.operation.CuteCurdOperation;
import com.cutefool.rds.meta.libs.RdsFields;
import com.cutefool.rds.meta.libs.RdsTable;
import com.cutefool.rds.template.RdsTemplate;
import com.cutefool.zero.code.admin.dbms.service.DbmsService;
import com.cutefool.zero.code.admin.dbms.support.DbmsExecutor;
import com.cutefool.zero.code.admin.meta.model.consts.ModelConsts;
import com.cutefool.zero.code.admin.meta.model.context.RdsTemplateContext;
import com.cutefool.zero.code.admin.meta.model.dto.ModelBasicDTO;
import com.cutefool.zero.code.core.domain.Db;
import com.cutefool.zero.code.core.domain.Model;
import jakarta.annotation.Resource;
import org.mybatis.dynamic.sql.SqlBuilder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class ModelDbSupport {

    @Resource
    private DbmsService dbmsService;

    @Resource
    private DbmsExecutor dbmsExecutor;

    @Resource
    private RdsTemplateContext rdsTemplateContext;

    @Resource
    private CuteCurdOperation<Model> cuteCurdOperation;

    public RdsTable doTableLibs(Model model) {
        // 查询对应的环境的配置
        Db devDb = dbmsService.getDevDb(model.getDbmsId());
        return ModelDbSupport.doTableLibs(model, devDb);
    }

    public static RdsTable doTableLibs(Model model, Db devDb) {
        RdsTable libs = new RdsTable();
        libs.setDbName(devDb.getName());
        libs.setName(model.getTableName());
        libs.setRemark(model.getDescription());
        return libs;
    }

    public void doSyncToDb(Long id) {
        QueryDsl<Model> queryDsl = QueryDsl.newInstance(Model.instance(), (where) -> where.and(Model.instance().id(), SqlBuilder.isEqualTo(id)));
        this.cuteCurdOperation.get(queryDsl).ifPresent(e -> {
            // 查询对应的环境的配置
            Db devDb = dbmsService.getDevDb(e.getDbmsId());
            dbmsExecutor.doInitFunction(devDb);
            RdsTemplate rdsTemplate = rdsTemplateContext.get(devDb);
            RdsTable rdsTableLibs = ModelDbSupport.doTableLibs(e, devDb);
            rdsTemplate.create(rdsTableLibs);
        });
    }


    public List<RdsFields> doSyncBasic(ModelBasicDTO dto) {
        List<RdsFields> rdsFields = new ArrayList<>();
        // 更新字段
        Byte softDelete = dto.getSoftDelete();
        if (Status.isTrue(softDelete)) {
            rdsFields.addAll(ModelConsts.fieldsMap.get(ModelConsts.SOFT_DELETE));
        }
        return rdsFields;
    }
}
